/**
 * 
 */
package com.jintian.smart.kernel.common.expr.op.define;

import com.jintian.smart.kernel.core.expr.IllegalExpressionException;
import com.jintian.smart.kernel.common.expr.datameta.BaseDataMeta;
import com.jintian.smart.kernel.common.expr.datameta.Constant;
import com.jintian.smart.kernel.common.expr.op.Operator;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 集合添加操作
 * 
 */
public class Op_APPEND extends Op_Base {
	public Op_APPEND() {
		super(Operator.APPEND);
	}

	public Constant execute(Constant[] args) throws IllegalExpressionException {
		Object[] params = this.getParameterValues(args);
		return append(params[0], params[1]);
	}

	/**
	 * 合并两个常量对象
	 * 
	 * @param object
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private Constant append(Object arg1, Object arg2) {
		if (arg1 == null || arg2 == null) {
			throw new IllegalArgumentException("操作符\"" + Operator.APPEND.getToken() + "\"参数丢失");
		}

		List<Object> resultCollection = new ArrayList<Object>();
		// 合并参数一
		if (arg1 instanceof Collection) {
			resultCollection.addAll((Collection) arg1);
		} else {
			resultCollection.add(arg1);
		}
		// 合并参数二
		if (arg2 instanceof Collection) {
			resultCollection.addAll((Collection) arg2);
		} else {
			resultCollection.add(arg2);
		}
		// 构造新的collection 常量
		Constant result = new Constant(BaseDataMeta.DataType.DATATYPE_LIST, resultCollection);
		return result;
	}

	public Constant verify(int opPositin, BaseDataMeta[] args) throws IllegalExpressionException {
		this.checkParameterCount(opPositin, args);
		// APPEND接受任何类型的参数，总是返回Collection类型的常量
		return new Constant(BaseDataMeta.DataType.DATATYPE_LIST, null);

	}

}
